package utils

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

type WeixinResponse struct {
	SessionKey string `json:"session_key"`
	UnionId    string `json:"unionid"`
	Errmsg     string `json:"errmsg"`
	Errcode    int    `json:"errcode"`
	OpenId     string `json:"openid"`
}

// 获取微信openid
func (w *WeixinResponse) GetWeixinOpenid(code, appid, secret string) error {
	client := &http.Client{Timeout: time.Minute} // 设置超市
	resp, err := client.Get(fmt.Sprintf(
		"https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
		appid,
		secret,
		code,
	))
	if err != nil {
		fmt.Println("get weixin openid err:", err)
		return err
	}
	defer resp.Body.Close()
	respData := make([]byte, 1024)
	n, err := resp.Body.Read(respData)
	if err != nil && err != io.EOF {
		fmt.Println("read response err:", err, n)
		return err
	}
	err = json.Unmarshal(respData[:n], &w)
	if err != nil {
		fmt.Println("unmarshal err:", err)
		return err
	}
	return nil
}
